import Taro, { useEffect, useState, useMemo, useReachBottom } from '@tarojs/taro'
import {View, Text, Image, Picker, ScrollView} from '@tarojs/components'
import { AtTabs, AtTabsPane, AtAccordion, AtIcon } from 'taro-ui'
import m from 'moment'
import cloneDeep from 'lodash/cloneDeep'
import './index.scss'

// components
import CashList from "../../components/cashList";
import NoData from "../../components/noData";

// api
import api from '../../api/index';

// utils
import getLoginInfo from "../../utils/getLoginInfo";
import getAvatarImgPrefix from "../../utils/getAvatarImgPrefix";

// constance
import {CASH_OUT_STATUS} from '../../constances/constances'

export default function WithDrawRecord() {
  const [userBankTransferList, setUserBankTransferList] = useState([])
  const [userBankStatements, setUserBankStatements] = useState([])
  const [balance, setBalance] = useState(0)
  const [current, setCurrent] = useState(0)
  const [loading, setLoading] = useState(false)
  const [isMore, setIsMore] = useState(false)
  const tabList = [{ title: '提现记录' }, { title: '账单明细' }]
  const PAGE_SIZE = 20

  useEffect( () => {
    const user = getLoginInfo()
    if(!user) {
      return
    }
    getCashOutData()
    getStatementData()
    getBalance()
  }, [])

  useReachBottom(() => {
    if (isMore) {
      getStatementData(userBankStatements.length, (userBankStatements.length + PAGE_SIZE - 1))
    }
  })

  // ---- 获取零钱
  async function getBalance() {
    const data  = await api.user.getUserBalance()
    if(data.code > 0) {
      setBalance(data.data / 100)
    }
  }
  // 获取零钱 ----

  // ---- 提现记录逻辑
  async function getCashOutData() {
    const data = await api.user.getUserCashOut({
      start: 0,
      end: 9999
    })
    if (data.code > 0) {
      const _userBankTransferList = JSON.parse(data.data).userBankTransferList
      if (_userBankTransferList.length > 0) {
        const _listData = _userBankTransferList.map(item => {
          const apply_year_month = m(item.apply_date).format('YYYY年MM月')
          const _listItem = {
            name: `${CASH_OUT_STATUS[item.operate_result]}`,
            num: '+' + item.transfer_cash_cent / 100,
            desc: `${m(item.apply_date).format('YYYY-MM-DD  HH:mm:ss')}`
          }
          return {
            ...item,
            ..._listItem,
            apply_year_month,
          }
        })

        setUserBankTransferList(_listData)
      }
    }
  }

  //  提现记录逻辑 ----


  // ---- 账单清单逻辑
    async function getStatementData(start = 0, end = PAGE_SIZE - 1) {
      setLoading(true)
      const data = await api.user.getStatement({
        start,
        end
      })
      setLoading(false)
      if(data.code > 0) {
        const _userBankStatements = JSON.parse(data.data).userBankStatements
        if(_userBankStatements) {
          const _listData = _userBankStatements.map(item => {
            const year_month = m(item.timeStamp).format('YYYY年MM月')
            const memoMap = {
              1: '返现',
              2: '提现',
            }
            const typeMap = {
              1: '+',
              2: ''
            }
            const _listItem = {
              title: item.memo ? item.memo : memoMap[item.type],
              desc: m(item.timeStamp).format('YYYY-MM-DD  HH:mm:ss'),
              money: item.moneyInCent / 100,
              icon: typeMap[item.type]
            }

            return {
              ...item,
              ..._listItem,
              year_month,
            }
          })

          if(_listData.length === PAGE_SIZE) {
            setIsMore(true)
          } else {
            setIsMore(false)
          }
          setUserBankStatements([
            ...userBankStatements,
            ..._listData,
          ])
        }

      }
    }

  // 账单清单逻辑 ----

  return (
    <View className='withdraw-record-page'>
      <View className='record-list-container'>
        <AtTabs current={current} tabList={tabList} onClick={value => setCurrent(value)}>
          <AtTabsPane current={current} index={0} >
            <View className='list-container'>

              {
                userBankTransferList.length > 0 ? (
                  userBankTransferList.map((item, index) => (
                    <View className='record-list-wrapper' key={index}>
                      <View className='statement-container'>
                        <View className='detail-container'>
                          <View className='detail'>
                            {
                              item.name
                            }
                          </View>
                          <View className='time'>
                            {
                              item.desc
                            }
                          </View>
                        </View>

                        <View className='money-container'>
                          {
                            item.num
                          }
                          <Image className='img' src={require('../../assets/coin24X24@2x.png')} />
                        </View>
                      </View>
                    </View>
                  ))
                ) : (
                  <View className='no-data'>
                    <NoData />
                  </View>
                )
              }
            </View>
          </AtTabsPane>

          <AtTabsPane current={current} index={1} >
            <View className='balance-container'>
              <View>账户余额 ¥{balance}</View>
            </View>
            {
              userBankStatements.length > 0 ? (
                <View className='list-container'>
                  {
                    userBankStatements.map((item, index) => (
                      <View className='record-list-wrapper' key={index}>
                        <View className='statement-container'>
                          <View className='detail-container'>
                            <View className='detail'>
                              {
                                item.title
                              }
                            </View>
                            <View className='time'>
                              {
                                item.desc
                              }
                            </View>
                          </View>

                          <View className='money-container'>
                            {
                              item.icon
                            }
                            {
                              item.money
                            }
                            <Image className='img' src={require('../../assets/coin24X24@2x.png')} />
                          </View>
                        </View>
                      </View>
                    ))
                  }
                  {
                    loading && (
                      <View className='tips'>
                        加载中...
                      </View>
                    )
                  }

                  {
                    !isMore && (
                      <View className='tips'>
                        没有更多记录咯~
                      </View>
                    )
                  }
                </View>
              ) : (
                <View className='no-data'>
                  <NoData />
                </View>
              )
            }
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  )
}

WithDrawRecord.config = {
  navigationBarTitleText: '提现记录',
}
